import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 定义设置和获取方法
  // 存入用户数据
  const user = ref(JSON.parse(localStorage.getItem('user'))) // 存入数据是一个对象类型
  const getToken = () => {
    return localStorage.getItem('token')
  }
  const token = ref(getToken() || '') // 已经实现双向数据绑定
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }
  const removeToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }
const getUser=()=>{
    user.value=JSON.parse(localStorage.getItem('user'))
}
const setUser=(newUser)=>{
    user.value=newUser
    localStorage.setItem('user',JSON.stringify(newUser))
 }
  // 用户登出
  const logout = () => {
    removeToken() // 清除token
    user.value = undefined //清除userInfo
    localStorage.removeItem('user')
  }
  // 导出token和用户数据
  return {
    token,
    setToken,
    removeToken,
    getUser,
    setUser,
    user,
    logout
  }
})